package BanyuanClub.Study.Day0310.生产者消费者模式;

/**
 * ArrayBlockingQueue
 * 有界阻塞队列
 * 生产者-消费者模式
 * 满-生产者会等待
 * 空-消费者会等待
 *
 * LinkedBlockingQueue
 * 无界的阻塞队列
 *
 * ConcurrentHashMap
 * 线程安全的map
 *
 */
public class MyArrayBlockingQueue {
    private Object[] arr;
    private int size;

    public MyArrayBlockingQueue(int limit) {
        this.arr = new Object[limit];
    }

    public synchronized void put(Object obj) throws InterruptedException {
        while (size == arr.length){
            System.out.println("已满");
            this.wait();
        }
        arr[size++] = obj;
        this.notifyAll();
        System.out.println("放一个");
    }
    public synchronized Object take() throws InterruptedException {
        while (size == 0){
            this.wait();
        }
        Object obj = arr[size--];
        arr[--size] = null;
        System.out.println("取一个");
        this.notifyAll();
        return obj;
    }

    public static void main(String[] args) {
        MyArrayBlockingQueue q = new MyArrayBlockingQueue(5);

        new Thread(() ->{
            while(true){
                try {
                    Thread.sleep(5000);
                    q.put("aaa");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(()->{
            while(true){
                try {
                    Thread.sleep(1000);
                    q.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
